//
//  RecommendVC.m
//  KeleAppProject
//
//  Created by Cen Zhou on 2018/1/11.
//  Copyright © 2018年 Cen Zhou. All rights reserved.
//

#import "RecommendVC.h"
#import "HomeTableViewCell.h"
#import "ZFVideoModel.h"
#import "ZFVideoResolution.h"
#import <ZFDownload/ZFDownloadManager.h>
#import "ZFPlayer.h"
#import "ShareView.h"
#import "HomeModel.h"
#import "VideoDetialVC.h"

static NSString *homeCell = @"homeCell";
@interface RecommendVC ()<ZFPlayerDelegate>

//@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray      *dataSource;
@property (nonatomic, strong) ZFPlayerView        *playerView;
@property (nonatomic, strong) ZFPlayerControlView *controlView;

@end

@implementation RecommendVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor redColor];
    CGRect frame = CGRectMake(0, 0, KLScreenW, KLScreenH-NaviH-TabbarH);
    self.view.frame = frame;
    self.pageNum = 1;
    [self getDataSourceWithPage:GET_PAGE_NEW start:self.pageNum];
    [self loadTableViewWithFrame:frame delegate:self];
    
    [self downRefresh];
    [self upLoadMore];
}

// 页面消失时候
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.playerView resetPlayer];
}



- (void)getDataSourceWithPage:(NSString *)page start:(NSInteger)start{
    
    NSLog(@"start === %ld",start);
    [[KeleData sharedInstance] recommendWithPage:[NSString stringWithFormat:@"%ld",start] pageNumber:PageNumStr success:^(id responseObject) {
        if ([responseObject[@"success"] integerValue] == 1) {
            NSArray *dataArray = responseObject[@"data"][@"pp"];
            NSMutableArray *tempDataArray = [NSMutableArray array];
            for (NSDictionary *dic in dataArray) {
                HomeModel *model = [HomeModel yy_modelWithDictionary:dic];
                [tempDataArray addObject:model];
            }
           
            [self refreshListData:tempDataArray flag:page];
            
            
        }
    } failure:^(NSError *error) {
        
    }];
   
    
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    // 这里设置横竖屏不同颜色的statusbar
    if (ZFPlayerShared.isLandscape) {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
    return ZFPlayerShared.isStatusBarHidden;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:homeCell];
    if (!cell) {
        cell = [[HomeTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:homeCell type:@"reommend"];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 取到对应cell的model
    __block HomeModel *model = self.sourceData[indexPath.row];
    // 赋值model
    cell.model = model;
    __block NSIndexPath *weakIndexPath = indexPath;
    __block HomeTableViewCell *weakCell     = cell;
    __weak typeof(self)  weakSelf = self;
    //
    weakCell.shareSignal = [RACSubject subject];
    [weakCell.shareSignal subscribeNext:^(id x) {
        NSLog(@"分享");
        
        ShareView *shareView = [[ShareView alloc]init];
        [self.view addSubview:shareView];
        [shareView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo([UIApplication sharedApplication].keyWindow);
        }];
        
    }];
    
    // 点击播放的回调
    cell.playBlock = ^(UIButton *btn){
        
        // 分辨率字典（key:分辨率名称，value：分辨率url)
//        NSMutableDictionary *dic = @{}.mutableCopy;
//        for (ZFVideoResolution * resolution in model.playInfo) {
//            [dic setValue:resolution.url forKey:resolution.name];
//        }
        // 取出字典中的第一视频URL
        NSURL *videoURL = [NSURL URLWithString:model.url];
        
        ZFPlayerModel *playerModel = [[ZFPlayerModel alloc] init];
        playerModel.title            = model.title;
        playerModel.videoURL         = videoURL;
//        playerModel.placeholderImageURLString = model.coverForFeed;
        playerModel.scrollView       = weakSelf.tableView;
        playerModel.indexPath        = weakIndexPath;
        // 赋值分辨率字典
//        playerModel.resolutionDic    = dic;
        // player的父视图tag
        playerModel.fatherViewTag    = weakCell.playView.tag;
        playerModel.fatherView = weakCell.playView;
        // 设置播放控制层和model
        [weakSelf.playerView playerControlView:nil playerModel:playerModel];
        // 下载功能
        weakSelf.playerView.hasDownload = YES;
        // 自动播放
        [weakSelf.playerView autoPlayTheVideo];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeModel *model = self.sourceData[indexPath.row];
    return [HomeTableViewCell getHeightWithData:model];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    VideoDetialVC *detialVc = [[VideoDetialVC alloc]init];
    [self.navigationController pushViewController:detialVc animated:YES];
}


- (ZFPlayerView *)playerView {
    if (!_playerView) {
        _playerView = [ZFPlayerView sharedPlayerView];
        _playerView.delegate = self;
        // 当cell播放视频由全屏变为小屏时候，不回到中间位置
        _playerView.cellPlayerOnCenter = NO;
    
        // 当cell划出屏幕的时候停止播放
//         _playerView.stopPlayWhileCellNotVisable = YES;
        //（可选设置）可以设置视频的填充模式，默认为（等比例填充，直到一个维度到达区域边界）
        // _playerView.playerLayerGravity = ZFPlayerLayerGravityResizeAspect;
        // 静音
        // _playerView.mute = YES;
        // 移除屏幕移除player
//         _playerView.stopPlayWhileCellNotVisable = YES;
        
//        _playerView.forcePortrait = NO;
        
        ZFPlayerShared.isLockScreen = YES;
        ZFPlayerShared.isStatusBarHidden = NO;
    }
    return _playerView;
}

- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [[ZFPlayerControlView alloc] init];
    }
    return _controlView;
}

#pragma mark - ZFPlayerDelegate

- (void)zf_playerDownload:(NSString *)url {
    // 此处是截取的下载地址，可以自己根据服务器的视频名称来赋值
    NSString *name = [url lastPathComponent];
    [[ZFDownloadManager sharedDownloadManager] downFileUrl:url filename:name fileimage:nil];
    // 设置最多同时下载个数（默认是3）
    [ZFDownloadManager sharedDownloadManager].maxCount = 4;
}


- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
